$.fn.longPress = function (fn) {
        var timeout = undefined;
        var $this = this;
        for (var i = 0; i < $this.length; i++) {
            $this[i].addEventListener('touchstart', function (event) {
                event.stopPropagation();
                timeout = setTimeout(fn, 800); //长按时间超过800ms，则执行传入的方法
            }, false);
            $this[i].addEventListener('touchend', function (event) {
                event.stopPropagation();
                clearTimeout(timeout); //长按时间少于800ms，不会执行传入的方法
            }, false);
        }
    }
    // 节点
const stature = document.querySelector('.stature'),
    weight = document.querySelector('.weight'),
    waistline = document.querySelector('.waistline'),
    mySickName = document.querySelector('.sick-list'),
    caseList = document.querySelector('.caselist'),
    totalSickList = document.querySelector('.total-sick-list'),
    cover = document.querySelector('.cover');

// 数据
var sickListArr = new Array(),
    totalListArr = new Array(),
    userId = null,
    caseListArr = new Array(),
    isDoctor = false;

//获取用户信息
(function () {
    var href = location.href;
    var params = href.split('?');
    userId = params[1].split('=')[1].split('&')[0];
    document.querySelector('.reliang').href = './quantitylist.html?userId=' + userId;
    if (params[1].split('=')[2] == 'patient') {
        document.title = '我的病例';
    } else {
        document.querySelector('.zhenduan').style.display = 'none';
        document.querySelector('.add_huayan').style.display = 'none';
        document.title = '他的病例';
        isDoctor = true;
    }
}());


//获取当前页面信息
(function () {
    $.ajax({
        url: baseUrl + '/patient/getPatientCasePage.do',
        type: 'GET', //GET
        async: true, //或false,是否异步
        data: {
            'userId': userId
        },
        timeout: 5000, //超时时间
        dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
        beforeSend: function (xhr) {
            document.querySelector('.spinner_cover').style.display = 'block';
        },
        success: function (data, textStatus, jqXHR) {
            document.querySelector('.spinner_cover').style.display = 'none';
            if (data.values) {
                stature.innerHTML = data.values.height + 'cm';
                weight.innerHTML = data.values.weight + 'kg';
                waistline.innerHTML = data.values.waist + 'cm';
                for (var i = 0; i < data.values.diagnosisList.length; i++) {
                    var element = data.values.diagnosisList[i];
                    sickListArr.push(element.diagnosisName);
                }
                switch (Number(data.values.level)) {
                    case 1:
                        document.querySelector('.li-weight').setAttribute('id', 'li-green');
                        break;
                    case 2:
                        document.querySelector('.li-weight').setAttribute('id', 'li-blue');
                    case 3:
                        document.querySelector('.li-weight').setAttribute('id', 'li-red');
                        break;
                    default:
                        break;
                }
                var totalWidth = null;
                //患者自己的个人病症列表
                for (var i = 0; i < sickListArr.length; i++) {
                    var element = sickListArr[i];
                    appendSickName(mySickName, element, sickListArr, 2, null);
                    totalWidth = document.querySelector('.sick-list').lastChild.offsetLeft + document.querySelector('.sick-list').lastChild.offsetWidth;
                    console.log(totalWidth);
                }
                mySickName.style.width = totalWidth + 'px';
                caseListArr = data.values.reportUrlList;
                //患者自己的个人病例列表
                for (var i = 0; i < caseListArr.length; i++) {
                    var element = data.values.reportUrlList[i];
                    if (element.scaledReprotUrl) {
                        createCase(element.createTime, element.scaledReprotUrl, element.reportId, null);
                    } else {
                        createCase(element.createTime, element.reportUrl, element.reportId, null);
                    }
                }
            }
        },
        error: function (xhr, textStatus) {
            document.querySelector('.spinner_cover').style.display = 'none';
            webToast("网络阻塞中...", "middle", 3000);
        },
        complete: function () {
            document.querySelector('.spinner_cover').style.display = 'none';
        }
    });

    //获取患者个人模版列表
    $.ajax({
        url: baseUrl + '/common/getDiagnosisList.do',
        type: 'GET', //GET
        async: true, //或false,是否异步
        data: {
            'userId': userId
        },
        timeout: 5000, //超时时间
        dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
        beforeSend: function (xhr) {
            document.querySelector('.spinner_cover').style.display = 'block';
        },
        success: function (data, textStatus, jqXHR) {
            document.querySelector('.spinner_cover').style.display = 'none';
            if (data.values) {
                totalListArr = data.values;
                for (var i = 0; i < totalListArr.length; i++) {
                    var element = totalListArr[i];
                    appendSickName(totalSickList, element.diagnosisName, totalListArr, 2, element.ifSystem);
                }
            }
        },
        error: function (xhr, textStatus) {
            document.querySelector('.spinner_cover').style.display = 'none';
            webToast("网络阻塞中...", "middle", 3000);
        },
        complete: function () {
            document.querySelector('.spinner_cover').style.display = 'none';
        }
    })
}());

//选择诊断病种
(function () {
    //显示
    var addB = document.querySelector('.zhenduan'),
        zhenduanbox = document.querySelector('.zhenduanbox'),
        diagnose = document.querySelector('.diagnose-btn'),
        sickName = document.querySelector('.importtext');
    addB.addEventListener('click', function () {
            cover.style.display = 'block';
        })
        //隐藏
    zhenduanbox.addEventListener('click', function (event) {
        event.stopPropagation();
    });
    cover.addEventListener('click', function (event) {
        event.stopPropagation();
        this.style.display = 'none';
    });
    diagnose.addEventListener('click', function (event) {
        var totalStr = totalListArr.join(','),
            sickListStr = sickListArr.join(',');
        if (totalStr.indexOf(sickName.value) == -1) {
            appendSickName(totalSickList, sickName.value, totalListArr, 1, null);
            totalListArr.push(sickName.value);
            cover.style.display = 'none';
        }
        if (sickListStr.indexOf(sickName.value) == -1) {
            appendSickName(mySickName, sickName.value, sickListArr, 1, null);
            sickListArr.push(sickName.value);
            var n = mySickName.offsetWidth + document.querySelector('.sick-list').lastChild.offsetWidth;
            mySickName.style.width = n + 'px';
        }
        sickName.value = '';
    })
}());


//隐藏遮罩层
var hidecover = function (ele, event) {
    ele.style.display = 'none';
};

//获取获得的图片
function previewImage(file) {
    caseList.style.display = "block";
    if (file.files && file.files[0]) {
        var form = new FormData();
        form.append("image", file.files[0]);
        var reader = new FileReader();
        reader.onload = function (evt) {
            createCase(null, evt.target.result, null, form);
        }
        reader.readAsDataURL(file.files[0]);
    }
}

//修改时间
var timechangemask = document.querySelector('.timechangemask'),
    timechange = document.querySelector('.timechange'),
    datesure = document.querySelector('.datesure'),
    timeInput = document.querySelector('.time-input');
datesure.addEventListener('click', function (event) {
    timechangemask.style.display = 'none';
    document.querySelector('.' + idN).innerHTML = timeInput.value;
});
timechange.addEventListener('click', function (event) {
    event.stopPropagation();
})
timechangemask.addEventListener('click', function (event) {
    event.stopPropagation();
    this.style.display = 'none';
});


//抽象方法，根据传入的数据来进行列表的渲染和添加事件
function appendSickName(ele, sickName, sicklistArr, type, isSystem) {
    var oLi = document.createElement('li'),
        oSpan = document.createElement('span');
    oSpan.style.display = 'none';
    oLi.setAttribute('class', 'sick-li' + sicklistArr.length);
    $(oLi).longPress(function () {
        if (isSystem && type == 2) {} else {
            oSpan.style.display = 'block';
        }
    });
    $(oLi).on('click', function () {
        oSpan.style.display = 'none';
    });
    if (type == 1) {
        if (ele == mySickName) {
            ajaxApi = baseUrl + '/patient/addDiagnosisType.do';
        } else {
            ajaxApi = baseUrl + '/patient/addUserDefinedDiagnosisType.do'
        }
        $.ajax({
            url: ajaxApi,
            type: 'GET', //GET
            async: true, //或false,是否异步
            data: {
                'userId': userId,
                "diagnosisName": sickName
            },
            timeout: 5000, //超时时间
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
                document.querySelector('.spinner_cover').style.display = 'block';
            },
            success: function (data, textStatus, jqXHR) {
                document.querySelector('.spinner_cover').style.display = 'none';
                if (data.errorcode == 000000) {

                } else {
                    webToast(data.errormsg, "middle", 3000);
                }
            },
            error: function (xhr, textStatus) {
                document.querySelector('.spinner_cover').style.display = 'none';
                webToast("网络阻塞中...", "middle", 3000);
            },
            complete: function () {
                document.querySelector('.spinner_cover').style.display = 'none';
            }
        })
    }

    var deleteApi = null;
    if (ele == mySickName) {
        deleteApi = baseUrl + '/patient/deleteDiagnosis.do';
    } else {
        oLi.addEventListener('click', function () {
            var totalStr = totalListArr.join(','),
                sickListStr = sickListArr.join(',');
            if (sickListStr.indexOf(sickName) == -1) {
                appendSickName(mySickName, sickName, sickListArr, 1);
                sickListArr.push(sickName);
                var n = mySickName.offsetWidth + document.querySelector('.sick-list').lastChild.offsetWidth;
                mySickName.style.width = n + 'px';
                cover.style.display = 'none';
            }
        })
        deleteApi = baseUrl + '/patient/deleteUserDefinedDiagnosis.do'
    }
    oSpan.addEventListener('click', function (event) {
        event.stopPropagation();
        $.ajax({
            url: deleteApi,
            type: 'GET', //GET
            async: true, //或false,是否异步
            data: {
                'userId': userId,
                "diagnosisName": sickName
            },
            timeout: 5000, //超时时间
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
                document.querySelector('.spinner_cover').style.display = 'block';
            },
            success: function (data, textStatus, jqXHR) {
                document.querySelector('.spinner_cover').style.display = 'none';
                if (data.errorcode == 000000) {
                    for (var i = 0; i < sicklistArr.length; i++) {
                        if (sickListArr[i] == sickName) {
                            sickListArr.splice(i, 1);
                        }
                    }
                    oSpan.parentElement.remove();
                } else {
                    webToast(data.errormsg, "middle", 3000);
                }
            },
            error: function (xhr, textStatus) {
                document.querySelector('.spinner_cover').style.display = 'none';
                webToast("网络阻塞中...", "middle", 3000);
            },
            complete: function () {
                document.querySelector('.spinner_cover').style.display = 'none';
            }
        })
    });

    oLi.innerHTML = sickName;
    oLi.appendChild(oSpan);
    ele.appendChild(oLi);
}

//创建病例单
function createCase(time, src, reportId, imagedata) {
    var oLi = document.createElement('li'),
        oSpan = document.createElement('span'),
        imgbox = document.createElement('div'),
        timebar = document.createElement('div'),
        dateBDiv = document.createElement('div'),
        saveBtn = document.createElement('button'),
        dateDiv = document.createElement('input'),
        bingliImage = document.createElement('img'),
        datuSpan = document.createElement('span');
    oSpan.setAttribute('class', 'delete');
    oSpan.style.display = 'none';
    oLi.setAttribute('class', 'clear');
    imgbox.setAttribute('class', 'clear imgbox');
    saveBtn.innerHTML = '保存';
    saveBtn.setAttribute('class', reportId)
    saveBtn.style.display = 'none';
    $(bingliImage).longPress(function () {
        oSpan.style.display = 'block';
    });
    $(oLi).on('click', function () {
        oSpan.style.display = 'none';
    });

    oSpan.addEventListener('click', function () {
        $.ajax({
            url: baseUrl + '/patient/deleteTestReport.do',
            type: 'GET', //GET
            async: true, //或false,是否异步
            data: {
                'reportId': saveBtn.getAttribute('class'),
            },
            timeout: 5000, //超时时间
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
                document.querySelector('.spinner_cover').style.display = 'block';
            },
            success: function (data, textStatus, jqXHR) {
                if (data.errorcode == 000000) {
                    document.querySelector('.spinner_cover').style.display = 'none';
                    oSpan.parentElement.remove();

                    // var totalStr = totalListArr.join(','),
                    //     sickListStr = sickListArr.join(',');
                } else {
                    webToast(data.errormsg, "middle", 3000);
                }
            },
            error: function (xhr, textStatus) {
                document.querySelector('.spinner_cover').style.display = 'none';
                webToast("删除图片失败", "middle", 3000);
            },
            complete: function () {
                document.querySelector('.spinner_cover').style.display = 'none';
            }
        });
    })
    saveBtn.addEventListener('click', function () {
        var n = dateDiv.value.split('-');
        $.ajax({
            url: baseUrl + '/patient/modifyReprotTime.do',
            type: 'GET', //GET
            async: true, //或false,是否异步
            data: {
                reportId: saveBtn.getAttribute('class'),
                date: new Date(n[0], n[1] - 1, n[2]).getTime()
            },
            timeout: 5000, //超时时间
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
                document.querySelector('.spinner_cover').style.display = 'block';
            },
            success: function (data, textStatus, jqXHR) {
                //需要排序
                document.querySelector('.spinner_cover').style.display = 'none';
                if (data.errorcode == 000000) {
                    var oUL = document.querySelector('.caselist');
                    for (var i = 0; i < oUL.children.length; i++) {
                        var element = oUL.children[i];
                        if (new Date(n[0], n[1] - 1, n[2]).getTime() >= element.getAttribute('id')) {
                            oUL.insertBefore(saveBtn.parentElement.parentElement.parentElement, element);
                            break;
                        } else {
                            if (i == oUL.children.length - 1) {
                                var temp = saveBtn.parentElement.parentElement.parentElement;
                                saveBtn.parentElement.parentElement.parentElement.remove();
                                oUL.appendChild(temp);
                            }
                        }
                    }
                    saveBtn.style.display = 'none';
                    webToast("修改时间成功", "middle", 3000);
                } else {
                    webToast(data.errormsg, "middle", 3000);
                }
            },
            error: function (xhr, textStatus) {
                document.querySelector('.spinner_cover').style.display = 'none';
                webToast("网络阻塞中...", "middle", 3000);
            },
            complete: function () {
                document.querySelector('.spinner_cover').style.display = 'none';
            }
        })
    })
    dateBDiv.setAttribute('class', 'dateBDiv');
    dateDiv.setAttribute('type', 'date');
    dateDiv.onchange = function () {
        saveBtn.style.display = 'inline-block';
    }
    if (time) {
        var y = new Date(time).getFullYear(),
            m = new Date(time).getMonth() + 1,
            dd = new Date(time).getDate();

        if (m.toString().length == 1) {
            m = '0' + m;
        }
        if (dd.toString().length == 1) {
            dd = '0' + dd;
        }
        dateDiv.value = y + '-' + m + '-' + dd;
    } else {
        var y = new Date().getFullYear(),
            m = new Date().getMonth() + 1,
            dd = new Date().getDate();
        if (dd.toString().length == 1) {
            dd = '0' + dd;
        }
        dateDiv.value = y + '-' + m + '-' + dd;
    }
    bingliImage.setAttribute('class', 'bingli');
    bingliImage.onload = function () {
        bingliImage.style.height = 5 * bingliImage.height / bingliImage.width + 'rem';
    }
    bingliImage.src = src;
    datuSpan.setAttribute('class', 'datu');
    //上传图片
    if (time) {
        imgbox.appendChild(oSpan);
        oLi.setAttribute('id', time);
        dateBDiv.appendChild(dateDiv);
        imgbox.appendChild(dateBDiv);
        imgbox.appendChild(bingliImage);
        imgbox.appendChild(datuSpan);
        if (!isDoctor) {
            dateBDiv.appendChild(saveBtn);
        } else {
            dateDiv.setAttribute('disabled', 'disabled')
        }
    } else {
        imagedata.append('userId', userId);
        imagedata.append('testReprotTime', new Date().getTime());
        var xhr = new XMLHttpRequest();　　　
        document.querySelector('.spinner_cover').style.display = 'block';　
        xhr.onprogress = function (event) {
            document.querySelector('.spinner_cover').style.display = 'none';
        }
        xhr.open('POST', baseUrl + '/patient/addTestReprot.do');　　　　 // 定义上传完成后的回调函数
        xhr.onload = function () {　　
            if (xhr.status === 200) {　　　　　
                saveBtn.setAttribute('class', JSON.parse(xhr.responseText).values.reportId)
                webToast("上传图片成功", "middle", 3000);
                imgbox.appendChild(oSpan);
                imgbox.appendChild(dateBDiv);
                dateBDiv.appendChild(dateDiv);
                imgbox.appendChild(bingliImage);
                imgbox.appendChild(datuSpan);
                if (!isDoctor) {
                    dateBDiv.appendChild(saveBtn);
                }
            } else {　　　　　　　　
                webToast(textStatus + '错误信息', "middle", 3000);　　
            }　　　　
        };　　　　
        xhr.send(imagedata);
    }
    oLi.appendChild(imgbox);
    caseList.appendChild(oLi);

    // 放大病例
    var bigcase = document.querySelector('.bigcase'),
        mask = document.querySelector('.mask');
    datuSpan.addEventListener('click', function () {
        datuSpan.style.display = 'none';
        $.ajax({
            url: baseUrl + '/patient/getRealReportUrl.do',
            type: 'GET', //GET
            async: true, //或false,是否异步
            data: {
                reportId: saveBtn.getAttribute('class'),
            },
            timeout: 5000, //超时时间
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
                document.querySelector('.spinner_cover').style.display = 'block';
            },
            success: function (data, textStatus, jqXHR) {
                //需要排序
                if (data.errorcode == 000000) {
                    bigcase.onload = function () {
                        document.querySelector('.spinner_cover').style.display = 'none';
                        bigcase.style.height = bigcase.width * document.body.clientWidth / bigcase.height;
                    }
                    bigcase.setAttribute('src', data.values.realReportUrl);
                } else {
                    webToast(data.errormsg, "middle", 3000);
                }
            },
            error: function (xhr, textStatus) {
                document.querySelector('.spinner_cover').style.display = 'none';
                webToast("网络阻塞中...", "middle", 3000);
            },
            complete: function () {
                // document.querySelector('.spinner_cover').style.display = 'none';
            }
        })
        mask.style.display = "table";
    });
    //点击隐藏
    mask.addEventListener('click', function () {
        datuSpan.style.display = 'block';
        this.style.display = 'none';
    })
}